import yfinance as yf
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# 获取天虹股票数据（股票代码：002419.SZ）
stock_code = "002419.SZ"
stock_data = yf.download(stock_code, start="2019-01-01", end="2024-12-31")

# 计算每日对数收益率
stock_data['Log Return'] = np.log(stock_data['Close'] / stock_data['Close'].shift(1))

# 计算每日对数收益率的均值和标准差
mean_return = stock_data['Log Return'].mean()
std_return = stock_data['Log Return'].std()

# 设置模拟参数
num_simulations = 20  # 模拟次数
num_days = 252  # 一年的交易日数量
last_price = stock_data['Close'].iloc[-1]  # 最后一个交易日的收盘价

# 创建一个矩阵存储所有模拟路径
simulated_prices = np.zeros((num_simulations, num_days))

# 蒙特卡洛模拟
for i in range(num_simulations):
    # 随机生成每日对数收益率的路径
    random_returns = np.random.normal(mean_return, std_return, num_days)
    # 计算股价路径
    simulated_prices[i, :] = last_price * np.exp(np.cumsum(random_returns))

# 绘制实际股价
plt.figure(figsize=(10, 6))
plt.plot(stock_data['Close'], label='实际股价', color='blue')

# 绘制所有模拟的股价路径
for i in range(num_simulations):
    plt.plot(pd.date_range(stock_data.index[-1], periods=num_days, freq='B'), simulated_prices[i, :], color='gray', alpha=0.3)

# 计算并绘制20条路径的覆盖区域
percentile_5 = np.percentile(simulated_prices, 5, axis=0)
percentile_95 = np.percentile(simulated_prices, 95, axis=0)
plt.fill_between(pd.date_range(stock_data.index[-1], periods=num_days, freq='B'), percentile_5, percentile_95, color='gray', alpha=0.3, label='模拟路径覆盖区域')

# 添加标签和图例
plt.title(f'天虹股票未来一年预测 (基于蒙特卡洛模拟)')
plt.xlabel('日期')
plt.ylabel('股价')
plt.legend()

# 显示图形
plt.tight_layout()
plt.show()
